// 等待页面加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    initCharts();
    
    // 初始化交互效果
    initInteractions();
    
    // 启动数据更新
    startDataUpdate();
});

// 初始化图表
function initCharts() {
    // 初始化分布图表
    initDistributionChart();
}

// 初始化人流量分布图表
function initDistributionChart() {
    const chartDom = document.getElementById('distributionChart');
    const myChart = echarts.init(chartDom);
    
    const option = {
        backgroundColor: 'transparent',
        grid: {
            left: '10%',
            right: '10%',
            top: '10%',
            bottom: '20%'
        },
        xAxis: {
            type: 'category',
            data: ['主题公园', '会展中心', '文化遗址', '乡村文旅', '商业街区'],
            axisLine: {
                lineStyle: {
                    color: 'rgba(0, 255, 255, 0.3)'
                }
            },
            axisLabel: {
                color: '#ffffff',
                fontSize: 10,
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: 'rgba(0, 255, 255, 0.3)'
                }
            },
            axisLabel: {
                color: '#ffffff',
                fontSize: 10
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(0, 255, 255, 0.1)'
                }
            }
        },
        series: [{
            data: [113, 349, 97, 33, 43],
            type: 'bar',
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(0, 255, 255, 0.8)' },
                    { offset: 1, color: 'rgba(0, 128, 255, 0.3)' }
                ]),
                borderColor: 'rgba(0, 255, 255, 0.5)',
                borderWidth: 1,
                shadowColor: 'rgba(0, 255, 255, 0.3)',
                shadowBlur: 10
            },
            emphasis: {
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 255, 255, 1)' },
                        { offset: 1, color: 'rgba(0, 128, 255, 0.5)' }
                    ]),
                    shadowColor: 'rgba(0, 255, 255, 0.5)',
                    shadowBlur: 20
                }
            },
            animationDelay: function (idx) {
                return idx * 100;
            }
        }],
        animationEasing: 'elasticOut',
        animationDelayUpdate: function (idx) {
            return idx * 50;
        }
    };
    
    myChart.setOption(option);
    
    // 响应式调整
    window.addEventListener('resize', function() {
        myChart.resize();
    });
    
    // 存储图表实例以便后续更新
    window.distributionChart = myChart;
}

// 初始化交互效果
function initInteractions() {
    // 功能按钮点击效果
    const funcButtons = document.querySelectorAll('.func-btn');
    funcButtons.forEach(button => {
        button.addEventListener('click', function() {
            const functionType = this.getAttribute('data-function');
            handleFunctionClick(functionType, this);
        });
        
        // 添加鼠标进入效果
        button.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-3px) scale(1.05)';
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
    
    // 景点卡片点击效果
    const attractionCards = document.querySelectorAll('.attraction-card');
    attractionCards.forEach(card => {
        card.addEventListener('click', function() {
            const attractionName = this.querySelector('.attraction-name').textContent;
            showAttractionDetails(attractionName);
        });
    });
    
    // 数据卡片悬停效果
    const dataCards = document.querySelectorAll('.data-card');
    dataCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 8px 40px rgba(0, 255, 255, 0.3)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 4px 20px rgba(0, 255, 255, 0.1)';
        });
    });
}

// 处理功能按钮点击
function handleFunctionClick(functionType, buttonElement) {
    // 移除所有按钮的激活状态
    document.querySelectorAll('.func-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 添加当前按钮的激活状态
    buttonElement.classList.add('active');
    
    // 添加点击动画
    buttonElement.style.animation = 'none';
    setTimeout(() => {
        buttonElement.style.animation = 'clickPulse 0.3s ease';
    }, 10);
    
    // 根据功能类型执行相应操作
    switch(functionType) {
        case 'operation':
            showOperationPanel();
            break;
        case 'flow':
            showFlowAnalysis();
            break;
        case 'monitor':
            showEnvironmentMonitor();
            break;
        case 'security':
            showSecurityPanel();
            break;
        case 'facility':
            showFacilityManagement();
            break;
        default:
            console.log('未知功能类型:', functionType);
    }
}

// 显示景点详情
function showAttractionDetails(attractionName) {
    // 创建模态框显示景点详情
    const modal = document.createElement('div');
    modal.className = 'attraction-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3>${attractionName}</h3>
                <button class="close-btn">&times;</button>
            </div>
            <div class="modal-body">
                <p>这里是${attractionName}的详细信息...</p>
                <div class="attraction-stats">
                    <div class="stat-item">
                        <span class="stat-label">当前人数:</span>
                        <span class="stat-value">${Math.floor(Math.random() * 100) + 20}人</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">推荐指数:</span>
                        <span class="stat-value">★★★★☆</span>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加样式
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
        animation: fadeIn 0.3s ease;
    `;
    
    document.body.appendChild(modal);
    
    // 关闭按钮事件
    modal.querySelector('.close-btn').addEventListener('click', () => {
        modal.style.animation = 'fadeOut 0.3s ease';
        setTimeout(() => {
            document.body.removeChild(modal);
        }, 300);
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.querySelector('.close-btn').click();
        }
    });
}

// 功能面板显示函数
function showOperationPanel() {
    console.log('显示运营态势面板');
    updateMapHighlight('operation');
}

function showFlowAnalysis() {
    console.log('显示客流分析面板');
    updateMapHighlight('flow');
    // 更新图表数据
    updateChartData();
}

function showEnvironmentMonitor() {
    console.log('显示环境监测面板');
    updateMapHighlight('monitor');
}

function showSecurityPanel() {
    console.log('显示智慧安保面板');
    updateMapHighlight('security');
}

function showFacilityManagement() {
    console.log('显示设施管理面板');
    updateMapHighlight('facility');
}

// 更新地图高亮
function updateMapHighlight(type) {
    const glowAreas = document.querySelectorAll('.glow-area');
    glowAreas.forEach(area => {
        area.style.animationDuration = '2s';
        area.style.background = getHighlightColor(type);
    });
}

// 获取高亮颜色
function getHighlightColor(type) {
    const colors = {
        operation: 'radial-gradient(circle, rgba(255, 165, 0, 0.4) 0%, transparent 70%)',
        flow: 'radial-gradient(circle, rgba(0, 255, 255, 0.4) 0%, transparent 70%)',
        monitor: 'radial-gradient(circle, rgba(0, 255, 0, 0.4) 0%, transparent 70%)',
        security: 'radial-gradient(circle, rgba(255, 0, 0, 0.4) 0%, transparent 70%)',
        facility: 'radial-gradient(circle, rgba(128, 0, 255, 0.4) 0%, transparent 70%)'
    };
    return colors[type] || 'radial-gradient(circle, rgba(0, 255, 255, 0.3) 0%, transparent 70%)';
}

// 启动数据更新
function startDataUpdate() {
    // 每30秒更新一次数据
    setInterval(() => {
        updateVisitorCount();
        updateRealtimeData();
        updateChartData();
    }, 30000);
    
    // 定时更新数据
    setInterval(() => {
        updateVisitorCount();
        updateRealTimeData();
        updateMonitorTime();
    }, 3000);

    // 初始化监控时间
    updateMonitorTime();
}

// 更新游客数量
function updateVisitorCount() {
    const countElement = document.querySelector('.visitor-count .count');
    const currentCount = parseInt(countElement.textContent);
    const newCount = currentCount + Math.floor(Math.random() * 10) - 5;
    const finalCount = Math.max(0, newCount);
    
    // 数字滚动效果
    animateNumber(countElement, currentCount, finalCount, 1000);
}

// 更新实时数据
function updateRealtimeData() {
    const realtimeItems = document.querySelectorAll('.realtime-item .item-value');
    realtimeItems.forEach(item => {
        const currentValue = parseInt(item.textContent.replace(/[^0-9]/g, ''));
        const change = Math.floor(Math.random() * 20) - 10;
        const newValue = Math.max(0, currentValue + change);
        
        if (item.textContent.includes('+')) {
            item.textContent = `+${newValue}人`;
        } else {
            item.textContent = `${newValue}人`;
        }
    });
}

// 更新图表数据
function updateChartData() {
    if (window.distributionChart) {
        const newData = [345, 113, 97, 33, 41].map(val => 
            val + Math.floor(Math.random() * 20) - 10
        );
        
        window.distributionChart.setOption({
            series: [{
                data: newData
            }]
        });
    }
}

// 更新监控时间
function updateMonitorTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    
    // 更新页面中的时间显示元素
    const timeElements = document.querySelectorAll('.monitor-time, .current-time');
    timeElements.forEach(element => {
        if (element) {
            element.textContent = timeString;
        }
    });
    
    console.log('更新监控时间:', timeString);
}

// 数字动画函数
function animateNumber(element, start, end, duration) {
    const startTime = performance.now();
    const difference = end - start;
    
    function updateNumber(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        const current = Math.floor(start + difference * progress);
        element.textContent = current.toString().padStart(5, '0');
        
        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        }
    }
    
    requestAnimationFrame(updateNumber);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeIn {
        from { opacity: 0; transform: scale(0.9); }
        to { opacity: 1; transform: scale(1); }
    }
    
    @keyframes fadeOut {
        from { opacity: 1; transform: scale(1); }
        to { opacity: 0; transform: scale(0.9); }
    }
    
    @keyframes clickPulse {
        0% { transform: scale(1); }
        50% { transform: scale(0.95); }
        100% { transform: scale(1); }
    }
    
    .func-btn.active {
        background: linear-gradient(45deg, rgba(0, 255, 255, 0.3), rgba(0, 128, 255, 0.3)) !important;
        border-color: rgba(0, 255, 255, 1) !important;
        box-shadow: 0 0 30px rgba(0, 255, 255, 0.5) !important;
    }
    
    .attraction-modal .modal-content {
        background: rgba(0, 20, 40, 0.95);
        border: 2px solid rgba(0, 255, 255, 0.5);
        border-radius: 15px;
        padding: 20px;
        max-width: 400px;
        width: 90%;
        backdrop-filter: blur(10px);
        box-shadow: 0 0 50px rgba(0, 255, 255, 0.3);
    }
    
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid rgba(0, 255, 255, 0.3);
    }
    
    .modal-header h3 {
        color: #00ffff;
        margin: 0;
    }
    
    .close-btn {
        background: none;
        border: none;
        color: #ffffff;
        font-size: 24px;
        cursor: pointer;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: all 0.3s ease;
    }
    
    .close-btn:hover {
        background: rgba(255, 0, 0, 0.2);
        color: #ff0000;
    }
    
    .attraction-stats {
        margin-top: 15px;
    }
    
    .stat-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
    }
    
    .stat-label {
        color: #a0a0a0;
    }
    
    .stat-value {
        color: #00ffff;
        font-weight: bold;
    }
`;
document.head.appendChild(style);

// 页面加载完成后的初始化
console.log('文旅可视化系统已加载完成');